package com.example.InetAddressDemos.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author Jason
 * @PACKAGE_NAME com.example.InetAddressDemos
 * @Description 接收数据
 * @date 2023-12-16 16:30
 */
public class ReceiveMessageUdpDemo {
    public static void main(String[] args) throws IOException {
        //接收数据
        //1.创建DatagramSocket对象
        //接受数据的时候一定要绑定数据
        //绑定的端口要跟发送的端口保持一致
        DatagramSocket ds = new DatagramSocket(10086);

        //2.接收数据
        //创建接收数据的数组
        byte[] bytes = new byte[1024];
        //创建DatagramPacket对象，封装数据，数据长度（表示使用全部长度接收数据）
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        ds.receive(dp);
        //3.解析数据
        byte[] data = dp.getData();
        int length = dp.getLength();
        InetAddress address = dp.getAddress();
        int port = dp.getPort();
        System.out.println("接收到数据: " + new String(data, 0, length));
        System.out.println("该数据从" + address + "这台电脑的" + port + "端口发送的");
        //4.关闭
        ds.close();
    }
}
